package com.example.springMVC.commons;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
@Log4j2
public class ServiceExceptionHandler implements HandlerExceptionResolver {

    @SneakyThrows
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView mav = new ModelAndView();
        ServiceException se = null;
        //判断异常类型
        if (e instanceof ServiceException) {
            se=(ServiceException) e;
        }else {
             se = new ServiceException("系统异常E");
        }
        log.error(e.getMessage());
        e.printStackTrace();
        //设置相应字符集 响应格式
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Cache-Control","no-cache,must-revalidate");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //将相应内容装成json字符串
        String jsonString = JSON.toJSONString(Result.error(e.getMessage()));
        httpServletResponse.getWriter().write(jsonString);
        return mav;
    }
}
